﻿(function ($, undefined) {

    // define the name of the UI component
    var ui_name = "usersAutocomplete"

    // initialize object
    var usersAutocomplete = $.usersAutocomplete = {

        // default values

        def: {
            userData: null, //默認數據
            groupData: null,
            width: "100%",
            addItem: false,
            removeItem: false,
            clickItem: function () { },
            completeOp: {}
        },
        setDefaults: function (defaultOptions) {
            this.defaults = $.extend({}, this.def, defaultOptions);
        }
    };

    $.fn.usersAutocomplete = function (options) {

        // method calling
        if (typeof options == 'string') {
            var args = Array.prototype.slice.call(arguments, 1),
			res;
            this.each(function () {
                var data = $.data(this, ui_name);
                if (data) {
                    var meth = data[options];
                    if (meth) {
                        var r = meth.apply(this, args);
                        if (res === undefined) {
                            res = r;
                        }
                    }
                }
            });
            if (res !== undefined) {
                return res;
            }
            return this;
        }

        // initialize options
        options = $.extend({}, usersAutocomplete.def, options);

        //var co = $.extend({ scroll: false, formatItem: function (row, i, max) { return row[0] + "[" + row[1] + "]"; } }, def.completeOp);

        var temp = '<span class="ez-usbox-item ${class}"><a><span>${text}</span><input type="hidden" value="${value}"/><img class="ez-usbox-del"/></a></span>';
        var lastData = null;
        var _pinyin = new Pinyin();
        var _idList = "";
        var _list = [];

        //user
        if (options.userData) {
            for (var key in options.userData) {
                var newUser = {
                    Name: options.userData[key].Name,
                    Id: options.userData[key].Id,
                    Tag: "user"
                }
                _list.push(newUser);
            }
        }

        //group
        if (options.groupData) {
            for (var key in options.groupData) {
                var newgroup = {
                    Name: options.groupData[key].Description,
                    Id: options.groupData[key].Memberstring,
                    Tag: "group"
                }
                _list.push(newgroup);
            }
        }

        
        this.each(function () {
            var _self = this;

            //initialize
            initUsBox();


            // initialize callback
            for (var key in options) {
                var value = options[key];
                if (typeof value == 'function') {
                    // bind callbacks
                    $(_self).bind(key, value);
                }
            }



            function initUsBox() {
                //dom
                var inc = $('<span class="ez-usbox-boxc"/>');
                var input = $('<input type="text"  style="border: 1px solid transparent;"  class="ez-usbox-txt"/>').appendTo(inc);

                $(_self).addClass("ez-usbox").width(options.width).append(inc);

                //event
                $(inc).click(function () {
                    $(input).focus();
                })

                $(input).keydown(function (e) {
                    if ($(this).val() == "" && e.keyCode == 8) {
                        if (lastData) {
                            removeitem(lastData, $('.ez-usbox-item:last'));
                        }
                    }

                })

                $(input).autocomplete({
                    source: function (req, add) {
                        if (!_list) {
                            return;
                        }

                        var keyWord = req.term.toLowerCase();
                        var suggestions = [];

                        $(_list).each(function (index, item) {

                            item.Pinyin = _pinyin.getFullChars(item.Name).toLowerCase()
                                                + _pinyin.getCamelChars(item.Name).toLowerCase();

                            if (!item.IsSelected && (item.Name.indexOf(keyWord) >= 0 || item.Pinyin.indexOf(keyWord) >= 0)) {
                                suggestions.push({ lable: item.Name, value: item.Name });

                            }
                        });

                        add(suggestions);

                    },
                    select: function (event, ui) {
                        var data = $.grep(_list, function (item) {
                            return item.Name == ui.item.value;

                        })[0];

                        lastData = data;
                        additem(data);

                    },
                    close: function (event, ui) {
                        $(this).clearFields();
                    }
                });
            }


            function unique(arry) {
                var a = {}; for (var i = 0; i < arry.length; i++) {
                    if (typeof a[arry[i]] == "undefined")
                        a[arry[i]] = 1;
                }
                arry.length = 0;
                for (var i in a)
                    arry[arry.length] = i;
                return arry;
            };

            function additem(data) {
                var ezclass = (data.Tag == "user" ? "ez-user" : "ez-group");
                var $item = $(temp.replace("${text}", data.Name).replace("${value}", data.Id).replace("${class}", ezclass));
                $item.find("img.ez-usbox-del").click(function () {
                    removeitem(data, $item);
                });

                $('.ez-usbox-boxc').before($item);

                var ids = _idList != "" ? _idList.split(",") : []

                // var idInGroup = data.Id.split(",");
                // ids = ids.concat(idInGroup);
                ids.push(data.Id);
                _idList = ids.join(",");
            }

            function removeitem(data, dom) {
                $(dom).remove();

                //todo:重搆双重循环
                var ids = _idList.split(",");
                var idIngroup = data.Id.split(",");

                for (var key in idIngroup) {
                    var index = -1;
                    for (var i = ids.length - 1; i >= 0; i--) {
                        if (idIngroup[key] == ids[i]) {
                            index = i;
                            break;
                        }
                    }
                    if (index > -1) {
                        ids.splice(index, 1);
                    }
                }


                _idList = ids.join(",");
            }


            var publicMethods = {
                getIdList: function () {
                    var idList = "";
                    if (_idList.indexOf('everyone') != -1)
                        idList = 'everyone';
                    else {
                        var ids = unique(_idList.split(','));
                        idList = ids.join(',');
                    }

                    return idList;
                },
                addUsers: function (users) {
                    for (var key in users) {
                        //todo 判断是user 还是 group
                        users[key].Tag = "user";

                        additem(users[key])
                    }
                }
            };

            $.data(this, ui_name, publicMethods);
        });

        return this;
    };



})(jQuery)




